package com.hy.frame.mvvm.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hy.frame.mvvm.state.ResultState
import com.hy.frame.mvvm.state.handle
import com.hy.frame.mvvm.state.handleException
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * title BaseViewModel
 * author HeYan
 * time 2021/6/18 下午2:16
 * desc 无
 */
abstract class BaseViewModel : ViewModel() {
    /**
     * 加载对话框
     */
    val loadingUI by lazy { MutableLiveData<Loading>() }

    /**
     * net request 不校验请求结果数据是否是成功
     * @param block 请求体方法
     * @param result 请求回调的ResultState数据
     * @param loadingEnabled 是否显示加载框
     * @param loadingMsg 加载框提示内容
     */
    protected fun <T> request(
        block: suspend () -> T,
        result: MutableLiveData<ResultState<T>>,
        loadingEnabled: Boolean = false,
        loadingMsg: String? = "加载中...",
        flag: String? = null
    ): Job {
        return viewModelScope.launch {
            runCatching {
                //加载中
                result.value = ResultState.newLoading(loadingMsg)
                if (loadingEnabled)
                    loadingUI.value = Loading(true, loadingMsg)
                //请求体
                block()
            }.onSuccess {
                if (loadingEnabled)
                    loadingUI.value = Loading(false)
                result.handle(it, flag)
            }.onFailure {
                it.printStackTrace()
                if (loadingEnabled)
                    loadingUI.value = Loading(false)
                result.handleException(it, flag)
            }
        }

    }

    /**
     * 加载模型
     * @param display 是否显示加载提示
     * @param display 提示内容
     */
    data class Loading(val display: Boolean, val msg: String? = null)
}